import { Sequelize, DataTypes } from 'sequelize';
import initializeDataBase from '@src/db/db';

import UserModel from './User';
import GroupModel from './Group';

const GroupMembersModel = async () => {
    const sequelize: Sequelize = await initializeDataBase();
    const GroupMembers = sequelize.define('groupmembers', {
        id: {
            type: DataTypes.INTEGER,
            primaryKey: true,
            autoIncrement: true
        },
        group_id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'groups',
                key: 'id'
            }
        },
        user_id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            references: {
                model: 'users',
                key: 'id'
            }
        },
        is_admin: {
            type: DataTypes.BOOLEAN,
            allowNull: false,
            defaultValue: false
        }
    })

    const User = await UserModel();
    const Group = await GroupModel();

    GroupMembers.belongsTo(User, { foreignKey: 'user_id' });
    GroupMembers.belongsTo(Group, { foreignKey: 'group_id' });

    await sequelize.sync({ alter: true }); // Sincroniza o modelo com o banco de dados
    return sequelize.models.groupmembers;
}

export default GroupMembersModel